package com.heima.wemedia.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.dtos.PageResult;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.threadlocal.UserThreadLocalUtils;
import com.heima.common.util.BeanHelper;
import com.heima.model.media.dtos.WmNewsDto;
import com.heima.model.media.dtos.WmNewsPageReqDto;
import com.heima.model.media.dtos.WmNewsResultDTO;
import com.heima.wemedia.entity.WmMaterial;
import com.heima.wemedia.entity.WmNews;
import com.heima.wemedia.service.WmNewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
public class WmNewsController {

    @Autowired
    private WmNewsService wmNewsService;

    @PostMapping("/api/v1/news/page")
    public PageResult<WmNewsResultDTO> findByPage(@RequestBody WmNewsPageReqDto dto){
        return wmNewsService.findByPage(dto);
    }

    /**
     * 新增，修改，提交
     * @param dto
     * @return
     */
    @PostMapping("/api/v1/news/submit")
    public ResponseResult submit(@RequestBody WmNewsDto dto){
        wmNewsService.submit(dto);
        return ResponseResult.ok();
    }

    /**
     * 根据id 查询
     * @param wmNewsId
     * @return
     */
    @GetMapping("/api/v1/news/one/{id}")
    public ResponseResult<WmNewsResultDTO> getWmNewsById(@PathVariable(name = "id")Integer wmNewsId){
        Integer userId = UserThreadLocalUtils.getUserId();
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmNews::getWmUserId,userId).eq(WmNews::getId ,wmNewsId);
        WmNews wmNews = wmNewsService.getOne(queryWrapper);
        if(wmNews == null){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        return ResponseResult.ok(BeanHelper.copyProperties(wmNews,WmNewsResultDTO.class));
    }

    /**
     * 文章上下架
     * @param dto
     * @return
     */
    @PutMapping("/api/v1/news/down_or_up")
    public ResponseResult downOrUp(@RequestBody WmNewsDto dto){
        wmNewsService.downOrUp(dto);
        return ResponseResult.ok();
    }
}
